package com.vbobot.demo.spring.nacos.client;


import java.io.IOException;
import java.util.Optional;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 这个同时实现在spring restTemplate的Interceptor和okhttp的Interceptor
 */
public final class SupportGetBodyInterceptor1 implements Interceptor {
    static ThreadLocal<Boolean> NEED_CONVERT = new ThreadLocal<>();
    static ThreadLocal<Request> BE_CONVERT_REQUEST = new ThreadLocal<>();

    static boolean needConvertToGet() {
        return Optional.ofNullable(NEED_CONVERT.get()).orElse(false);
    }

    /**
     * okhttp的拦截，让实际发送get请求
     */
    @Override
    public Response intercept(Chain chain) throws IOException {
        try {
            final Request request = chain.request();
            if (needConvertToGet()) {
                BE_CONVERT_REQUEST.set(request);
            }
            return chain.proceed(request);
        } finally {
            BE_CONVERT_REQUEST.remove();
        }
    }
}